/**
 +------------------------------------------------------------------------------
 * Author Ding Xin
 +------------------------------------------------------------------------------
 * operate.js
 * 2015-05-26
 +------------------------------------------------------------------------------
 */
var express = require('express');
var router = express.Router();
var fields = {
    user: String,
    modules: String,
    top: String,
    left: String,
    tableTextRow: String,
    tableTextColumn: String,
    list: String,
    textareaWidth: String,
    textareaHight: String,
    formType: String,
    tableTs: String
};

var Modules = require('../schema/modules');
var fs = require('fs');

var file_size = 102410241024; //1G
var buf_size = 10240;
var buf = new Buffer('buf_size');

var LMenu = require('../schema/LMenu');
var operateRight;

router.get('/', function(req, res, next) {
    //node是异步的，所以在查询数据库成功后render页面
    if(req.cookies.user) {
        getLeftData(req, res);
    } else {
        res.redirect('/main');
    } 
})

/* post login ajax request */
router.post('/status', function(req, res, next) {

    var user = req.body.user,
        leftMenu = req.body.leftMenu,
        flug = 0;
    Modules.find({
        user: user,
        leftMenu: leftMenu
    }, function(err, docs) {
        if (err) {
            console.log(err);
        }
        Modules.remove({
            user: user,
            leftMenu: leftMenu
        }, function() {
            if (req.body.dataArray) {
                for (var i = 0; i < req.body.dataArray.length; i++) {
                    var _modules = new Modules(req.body.dataArray[i]);
                    _modules.save(function(err, user) {
                        if (err) {
                            console.log(err);
                            flug = 1;
                        }
                    });
                };
                if (flug === 0) {
                    res.send("ok");
                };
                if (flug === 1) {
                    res.send("error");
                };
            };
        });
    })

});


/* post login ajax request */
router.post('/export', function(req, res, next) {
    var user = req.body.user;
    LMenu.find({
        user: req.cookies.user.trim(),
        module: '1'
    })
        .sort({
            '_id': 1
        })
        .exec(function(err, menus) {
            var data = fs.readFileSync("./packageGenerator/index.html", "utf-8"),
                tpl;
                console.log(data);
            for (var i = 0, len = menus.length; i < len; i++) {
                console.log(menus[i]._id);
                var aaa = controlLeftMsg(menus, '', '0', menus[i]._id);
                tpl = data.replace('<@@-leftMsg-@@>', aaa);
                (function(i, tpl) {
                    Modules.find({
                        user: req.cookies.user.trim(),
                        leftMenu: menus[i]._id
                    }).sort({
                        'top': 1
                    }).exec(function(err, result) {
                        rightMsg = controlRightMsg(result);
                        tpl = tpl.replace('<@@-rightMsg-@@>', rightMsg);
                        fs.writeFile("./packageGenerator/page" + menus[i]._id + ".html", tpl, "utf-8", function() {
                            if (i === len - 1) {
                                res.send("ok");
                            };
                        })
                    })
                })(i, tpl)
            }
        })
});


function controlLeftMsg(menus, _id, rank, lia_id) {
    var html = '';
    for (var i = 0; i < menus.length; i++) {
        var data = '';
        if (menus[i].M_rank == rank && menus[i].pre_id == _id) {
            console.log("lia_id" + lia_id);
            console.log("menus[i]._id" + menus[i]._id);
            if (lia_id === menus[i]._id) {
                data = '<div class="menu" data-menu>' +
                    '<div class="txt current" data-txt>' +
                    '<a href="page' + menus[i]._id + '.html">' + menus[i].M_name + '</a>' +
                    '</div>' + controlLeftMsg(menus, menus[i]._id, +rank + 1, lia_id) + '</div>';
            } else {
                data = '<div class="menu" data-menu>' +
                    '<div class="txt" data-txt>' +
                    '<a href="page' + menus[i]._id + '.html">' + menus[i].M_name + '</a>' +
                    '</div>' + controlLeftMsg(menus, menus[i]._id, +rank + 1, lia_id) + '</div>';
            }
            html += data;
        } else if (menus[i].M_rank == rank) {
            data = '';
            html += data;
        }
    }

    return html;
}

/* post login ajax request */
router.post('/initializeRight', function(req, res, next) {

    /* 查看是否存在下级菜单 */
    var user = req.body.user,
        leftMenu = req.body.leftMenu;
    Modules.find({
        user: req.cookies.user.trim(),
        leftMenu: leftMenu
    }).sort({
        'top': 1
    }).exec(function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result.length === 0) {
            res.send("empty");
        } else {
            rightMsg = controlRightMsg(result);
            res.send(rightMsg);
        }
    })
})

function controlRightMsg(right) {
    var data = "";
    right.forEach(function(name) {
        switch (name.modules) {
            case "list":
                {
                    data += '<ul class="rightTextList canMove brick" data-module="list"><li>内容1内容1内容1</li><li>内容2内容2内容2</li><li>内容3内容3内容3</li><li>内容4内容4内容4</li><li>内容5内容5内容5</li></ul>'
                    break;
                }
            case "table":
                {
                    data += '<table class="rightTableStyle brick canMove" data-module="table" data-row="' + name.tableTextRow + '" data-column="' + name.tableTextColumn + '" data-ts="' + name.tableTs + '">' +
                        '<tbody>';
                    var lin, tr, td = "<td>内容</td>",
                        th = "<th>内容</th>";
                    switch (name.tableTs) {
                        case "ts1":
                            {
                                lin = "";
                                for (var i = 0; i < name.tableTextColumn; i++) {
                                    lin += td;
                                }
                                tr = "<tr>" + lin + "</tr>";
                                lin = "";
                                for (var i = 0; i < name.tableTextRow; i++) {
                                    lin += tr;
                                }
                            }

                            data += lin;
                            break;
                        case "ts2":
                            {
                                lin = "";
                                lin1 = "";
                                for (var i = 0; i < name.tableTextColumn; i++) {
                                    lin += td;
                                }
                                tr = "<tr>" + lin + "</tr>";
                                for (var i = 0; i < name.tableTextColumn; i++) {
                                    lin1 += th;
                                }
                                lin = "<tr>" + lin1 + "</tr>";
                                for (var i = 1; i < name.tableTextRow; i++) {
                                    lin += tr;
                                }
                            }
                            data += lin;
                            break;
                        case "ts3":
                            {
                                lin = "";
                                lin1 = "";
                                lin += th;
                                for (var i = 1; i < name.tableTextColumn; i++) {
                                    lin += td;
                                }
                                tr = "<tr>" + lin + "</tr>";
                                for (var i = 0; i < name.tableTextColumn; i++) {
                                    lin1 += th;
                                }
                                lin = "<tr>" + lin1 + "</tr>";
                                for (var i = 1; i < name.tableTextRow; i++) {
                                    lin += tr;
                                }
                            }
                            data += lin;
                            break;
                    }
                    data += '</tbody></table>';
                    break;
                }
            case "form":
                {
                    var divDom = '<div class="canMove brick small" data-module="form">',
                        inputText = '<input type="'+name.formType+'" name="rightMoudle-button1" class="rightInputStyle">';
                    if (name.inputLabel === "yes") {
                        divDom +='<label class="addlabel">添加内容:</label>';
                    }
                    divDom += inputText;
                    switch (name.formType) {
                        case "file":
                        case "hidden":
                        case "image":
                        case "password":
                        case "reset":
                        case "submit":
                        case "text":
                            break;
                        case "button":{
                                                divDom = '<div class="canMove brick small" data-module="form">';
                                                inputText = '<input type="'+name.formType+'" name="rightMoudle-button1" class="rightInputStyle" value="按钮">';
                                            
                    if (name.inputLabel === "yes") {
                        divDom +='<label class="addlabel">添加内容:</label>';
                    }
                                            divDom += inputText;}
                            break;
                        case "checkbox":
                            divDom +='<label class="addLabelText">checkbox 内容</label>';
                            break;
                        case "radio":
                            divDom +='<label class="addLabelText">radio 内容</label>';
                            break;
                    }
                    divDom +='</div>';
                    data += divDom;
                    break;
                }
            case "textarea":
                {
                    data += '<div class="textareaDiv brick canMove" data-module="textarea"><textarea class="rightTextStyle" style="width: ' + name.textareaWidth + ';  height: ' + name.textareaHight + ';">文本信息文本信息</textarea></div>';
                    break;
                }
        }
    });
    return data;
}


function createHtml(menus, _id, rank) {
    var html = '';
    for (var i = 0; i < menus.length; i++) {
        var data = '';
        if (menus[i].M_rank == rank && menus[i].pre_id == _id) {
            data = '<div class="menu" style="display:block" data-menu=' + rank + '>' +
                '<div class="txt" data-txt data-id=' + menus[i]._id + '>' +
                '<img src="/static/static/images/delete.png" class="delete"/>' +
                '<img src="/static/static/images/add.png" class="add"/>' +
                '<a href="javascript:;">' + menus[i].M_name + '</a>' +
                '</div>' + createHtml(menus, menus[i]._id, +rank + 1) + '</div>';
            html += data;
        } else if (menus[i].M_rank == rank) {
            data = '';
            html += data;
        }
    }
    return html;
}

function getLeftData(req, res) {
    //找出该用户拥有的所有menu,按时间排序
    LMenu.find({
        user: req.cookies.user.trim(),
        module: '1'
    }).sort({
        '_id': 1
    })
        .exec(function(err, menus) {
            //对数据进行分级
            var data = createHtml(menus, '', '0');
            getRightData(req, res, data);
        })
}

function getRightData(req, res, data) {
    Modules.find({
        user: req.cookies.user.trim(),
    }).sort({
        'top': 1
    }).exec(function(err, result) {
        res.render('operate/index', {
            left: data,
            right: result,
            user: req.cookies.user.trim(),
        });
    })
}

module.exports = router;